package routers

import (
	"wx-uniapp-go/internal/middleware"
	"wx-uniapp-go/runtime"

	"wx-uniapp-go/third_party/cdslog"
	reqlogexporter "wx-uniapp-go/third_party/cdsreq/exporter"
	reqloggin "wx-uniapp-go/third_party/cdsreq/gin"
	reqlogoptions "wx-uniapp-go/third_party/cdsreq/options"
	reqlogtrace "wx-uniapp-go/third_party/cdsreq/trace"

	"github.com/gin-gonic/gin"
)

var engine *gin.Engine

func SetEngine(e *gin.Engine) {
	engine = e
}

func Init() {
	engine.Use(gin.Logger())
	engine.Use(middleware.GinRecovery())
	//engine.Use(reqlog.ReqLogFunc())
	//if  runtime.RunMode == runtime.DEV {
	//	engine.Use(middleware.Cors()) // cors跨域 nginx已统一配置跨域，配置两次会导致重复跨域
	//}
	//输入输出
	engine.Use(reqRsp())

	InitUserRoute()
	InitProductRoute()
	InitCartRoute()
	InitRedPacketRoute()
	InitSignInRoute()
}

func reqRsp() gin.HandlerFunc {
	var tIdProvider reqlogtrace.TraceIdProvider
	if runtime.RunMode == runtime.DEV {
		tIdProvider = reqlogtrace.NewHeaderProvider()
	} else {
		tIdProvider = reqlogtrace.NewOtelProvider()
	}
	return reqloggin.ReqLogMiddleware(
		reqlogoptions.NewConfig(
			reqlogoptions.WithTraceIDProvider(tIdProvider),
			reqlogoptions.WithExporter(
				reqlogexporter.NewCdsLogExporter(
					reqlogexporter.NewConfig(
						reqlogexporter.WithCdslogger(cdslog.GetLogger()),
						reqlogexporter.WithOutputEnabled(false),
					),
				),
			),
		),
	)
}
